/*global $config define Base64 document $win:true*/
define(["jquery", "jquery-knob"], function($) {
    function DefaultProxy(scheme, helper) {
        this.helper = helper;
        this.scheme = scheme;
        this.proxyName = "proxy_default";

        // downloader
        this._downloadQueue = {};
    }
    DefaultProxy.METHOD_TAKE_PHOTO = "take_photo";
    DefaultProxy.METHOD_BACKWARD = "backward";
    DefaultProxy.METHOD_NEWWIN = "newwin";
    DefaultProxy.METHOD_CANCEL = "cancel";
    DefaultProxy.METHOD_CANCEL_ALL = "cancel_all";
    DefaultProxy.METHOD_SHOW_IMAGES = "show_images";
    DefaultProxy.METHOD_TAKE_ALBUM = "take_album";
    DefaultProxy.METHOD_SCAN_QRCODE = "scanqrcode";
    DefaultProxy.METHOD_TAKE_CALL = "take_call";
    DefaultProxy.METHOD_TEMP_FOLDER_SIZE = "temp_folder_size";
    DefaultProxy.METHOD_CLEAR_TEMP_FOLDER = "clear_temp_folder";
    DefaultProxy.METHOD_LOAD_AUDIO = "load_audio";
    DefaultProxy.METHOD_PLAY_AUDIO = "play_audio";
    DefaultProxy.METHOD_CLOSE_AUDIO = "close_audio";
    DefaultProxy.METHOD_OPEN_AUDIO = "open_audio";
    DefaultProxy.METHOD_RELEASE_AUDIO = "release_audio";
    DefaultProxy.METHOD_GET_DATA = "get_data";


    DefaultProxy.prototype.getTempFolderSize = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_TEMP_FOLDER_SIZE, {}, callback);
    };

    DefaultProxy.prototype.clearTempFolder = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_CLEAR_TEMP_FOLDER, {}, callback);
    };

    DefaultProxy.prototype.takePhoto = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_TAKE_PHOTO, {}, callback);
    };

    DefaultProxy.prototype.takePhoto = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_TAKE_PHOTO, {}, callback);
    };

    DefaultProxy.prototype.takeCall = function(phone) {
        if(typeof phone == "undefined" || phone.length == 0) {
            return;
        }
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_TAKE_CALL, {phone: phone}, null);
    };

    DefaultProxy.prototype.showImages = function(params) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_SHOW_IMAGES, params, null);
    };

    DefaultProxy.prototype.takeAlbum = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_TAKE_ALBUM, {}, callback);
    };

    DefaultProxy.prototype.scanQrcode = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_SCAN_QRCODE, {}, callback);
    };

    DefaultProxy.prototype.loadAudio = function(uri, callback) {
        var param = {
            key: $.b(uri, 0),
            src: uri
        };
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_LOAD_AUDIO, param, callback);
        return param.key;
    };

    DefaultProxy.prototype.playAudio = function(key, status) {
        var param = {
            key: key,
            status: status
        };
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_PLAY_AUDIO, param, null);
    };

    DefaultProxy.prototype.closeAudio = function() {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_CLOSE_AUDIO, {}, null);
    };

    DefaultProxy.prototype.openAudio = function() {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_OPEN_AUDIO, {}, null);
    };

    DefaultProxy.prototype.releaseAudio = function() {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_RELEASE_AUDIO, {}, null);
    };

    // 获取数据
    DefaultProxy.prototype.getData = function(data, success) {
        data = $.extend({
            url: {}
        }, data);

        if($config.debug) {
            var url = $config.getDebugReqUrl(data.url.local);
            return $.post(url, data, success);
        } else {
            this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_GET_DATA + "." + (new Date()).getTime() + "_" + Math.floor(Math.random() * 1000), data, success);
        }
    };

    //下载功能begin
    /**
     * domArray: 绑定下载的jquery dom对象
     * callback:
     *		onPaused: 暂停任务时的回调
     *		onComplete: 完成时执行的回调
     *      onProgress: 下载过程中执行的回调
     *      onError: 下载失败时执行的回调
     */
    DefaultProxy.prototype.initDownload = function(domArray, callback) {
        var _this = this;
        domArray.each(function() {
            var item = $(this);
            var flag = item.attr("has-init-downloader");
            if (flag != "true") {
                item.attr("has-init-downloader", "true");
                _this.download(item, callback);
            }
        });
    };

    /**
     * item: 绑定下载的jquery dom对象。
     *			注意，该jquery对象必须已经被添加到dom中
     * callback:
     *      onPaused: 暂停任务时的回调
     *		onComplete: 完成时执行的回调
     *      onProgress: 下载过程中执行的回调
     *      onError: 下载失败时执行的回调
     */
    DefaultProxy.prototype.download = function(item, callback) {
        var _this = this;

        if (!item) {
            $win.log("downloader: no dom");
            return;
        }
        var fileType = item.attr("file-type");
        var fileUrl = item.attr("file-url");
        var imageType = item.attr("image-type");
        var imageScale = item.attr("image-scale");
        if (!$.isNotBlank(imageType)) {
            imageType = "default";
        }

        if (!$.isNotBlank(fileUrl) || !$.isNotBlank(fileType)) {
            $win.log("downloader: neither file url nor file type is defined");
            return;
        }

        var params = $.extend({}, callback);
        params.item = item;
        params.url = fileUrl;
        params.fileType = fileType;
        params.imageType = imageType;

        // 下载前的处理
        if (params.fileType == "pic") {
            // 处理图片
            params.item.addClass("image-waiting");
            var heart = $("<div class=\"heart\"><div>");
            params.item.append(heart);
            if (imageScale && !JSON.parse(imageScale)) {
                params.imageWidth = 0;
            } else {
                params.imageWidth = params.item.width();
            }
        } else if (params.fileType == "audio") {
            // 先不下载，点击时在下载，下载完成自动播放
            var $audio = $("<div class=\"file-audio audio-play\"></div>");
            params.item.append($audio);
            $audio.click(function(event) {
                $(this).hide();

                // 处理音频样式
                var $progress = $("<div class=\"audio_progress\"></div>");
                params.item.append($progress);
                var width = item.width();
                var height = item.height();
                var domWidth = (width > height)
                    ? height / 2
                    : width / 2;
                domWidth = domWidth > 30
                    ? 30
                    : domWidth;
                $progress.knob({readOnly: true, width: domWidth, height: domWidth});
                params.item.$progress = $progress;

                _this._doDownload(params);

                event.preventDefault();
                event.stopPropagation();
            });
        }

        var key = $.b(params.url, 0);
        if (this._downloadQueue.hasOwnProperty(key)) {
            this._downloadQueue[key].push(params);
        } else {
            this._downloadQueue[key] = new Array();
            this._downloadQueue[key].push(params);

            if (params.fileType == "pic") {
                this._doDownload(params);
            }
        }
    };

    DefaultProxy.prototype.startDownload = function(dom) {
        var url = dom.attr("file-url");
        var key = $.b(url, 0);
        var params = {};
        params.url = url;
        if (this._downloadQueue.hasOwnProperty(key)) {
            this._doDownload(this._downloadQueue[key][0]);
        }
    };

    // @deprecated
    DefaultProxy.prototype.changeStatus = function(dom, status) {
        var url = dom.attr("file-url");
        var key = $.b(url, 0);
        if (this._downloadQueue[key]) {
            var task = this._downloadQueue[key];
            if (task.item) {
                var $audio = task.item.find(".file-audio");
                if ($audio) {
                    if (status == "pause") {
                        $audio.attr("playing", false);
                        $audio.removeClass("audio-stop").addClass("audio-play");
                    } else if (status == "start") {
                        $audio.attr("playing", true);
                        $audio.removeClass("audio-play").addClass("audio-stop");
                    }
                    $audio.hide().show(0);
                }
            }
        }
    };

    DefaultProxy.prototype._doDownload = function(params) {
        var requestPath = "http://downloadfile?src=" + Base64.encode(params.url) + "&type=" + params.fileType + "&_t=" + (new Date().getTime());
        if (params.imageWidth) {
            requestPath += "&width=" + params.imageWidth;
        }
        var tempImg = $("<img src=\"" + requestPath + "\" width=\"0px\" height=\"0px\" style=\"display:none;\"/>");
        params.item.append(tempImg);
    };

    DefaultProxy.prototype.cb_downloader = function(params) {
        if (!params.hasOwnProperty("url")) {
            $win.log("downloader callback: no url is defined");
            return;
        }
        var key = $.b(params.url, 0);
        if (this._downloadQueue.hasOwnProperty(key)) {
            var tasks = this._downloadQueue[key];
            for (var i = 0; i != tasks.length; i++) {
                var task = $.extend(tasks[i], params);
                this._downloadCb(task);
            }
        } else {
            $win.log("no task found");
        }
    };

    DefaultProxy.prototype._downloadCb = function(task) {
        switch (task.textStatus) {
            case "complete":
                this._doComplete(task);
                this._finishDownload(task);
                break;
            case "paused":
                if (task.onPaused && typeof(task.onPaused) == "function") {
                    task.onPaused.call(this, task);
                }
                break;
            case "error":
                this._doError(task);
                this._finishDownload(task);
                break;
            case "progress":
                this._doProgress(task);
                break;
        }
    };

    DefaultProxy.prototype._finishDownload = function(task) {
        var key = $.b(task.url, 0);
        if (this._downloadQueue.hasOwnProperty(key)) {
            delete this._downloadQueue[key];
        }
    };

    DefaultProxy.prototype._doError = function(task) {
        var item = task.item;
        if (task.fileType == "pic") {
            // 取消动画
            item.removeClass("image-waiting");
            item.find(".heart").remove();
            item.find("img").remove();

            // 设置加载失败图片
            item.addClass("image-failed");
        } else if (task.fileType == "audio") {
            item.find("img").remove();
            if (item.$progress) {
                item.$progress.parent().remove();
            }
            var $audio = item.find(".file-audio");
            if ($audio) {
                $audio.show();
            }
        }

        if (task.onError && typeof(task.onError) == "function") {
            task.onError.call(this, task);
        }
    };

    DefaultProxy.prototype._doProgress = function(task) {
        task.item.find("img").hide();
        var $progress = task.item.$progress;
        if ($progress) {
            var progress = parseInt(parseInt(task.current) / parseInt(task.total) * 100);
            if (progress > 0) {
                $progress.val(progress).trigger("change");
            }
        }

        if (task.onProgress && typeof(task.onProgress) == "function") {
            task.onProgress.call(this, task);
        }
    };

    DefaultProxy.prototype._doComplete = function(task) {
        var _this = this;
        // 处理图片
        var item = task.item;
        if (task.fileType == "pic") {
            // 取消动画
            item.removeClass("image-waiting");
            item.find(".heart").remove();
            item.find("img").remove();

            // 加载本地图片
            var url = "localfile?src=" + Base64.encode(task.path);
            item.css("background-image", "url('" + url + "')");
            item.css("background-repeat", "no-repeat");
            switch (task.imageType) {
                case "fitXY":
                    item.css("background-position", "center");
                    item.css("background-size", "100% 99.9%");
                    break;
                case "fitCenter":
                    item.css("background-position", "center");
                    item.css("background-size", "contain");
                    break;
                case "center":
                    item.css("background-position", "center");
                    break;
                case "circle":
                    item.css("background-position", "center");
                    item.css("background-size", "100% 99.9%");
                    var radius = item.width();
                    item.css("border-radius", (radius / 2) + "px");
                    break;
                case "centerCrop":
                    item.css("background-position", "center");
                    item.css("background-size", "cover");
                    break;
                case "fitWidth":
                    url = "http://" + url;
                    var $img = $("<img src=\"" + url + "\" style=\"display:none;\"/>");
                    $img.get(0).onload = function() {
                        // 获取文件宽高
                        var imgWidth = $img.width();
                        var imgHeight = $img.height();
                        // 计算item自动拉伸的高度
                        var itemHeight = item.width() * imgHeight / imgWidth;
                        item.height(itemHeight);
                        // 设置背景fitXY
                        item.css("background-position", "center");
                        item.css("background-size", "100% 99.9%");
                        // 删除img
                        $img.remove();
                        if (task.onComplete && typeof(task.onComplete) == "function") {
                            task.onComplete.call(_this, task);
                        }
                    };
                    $(document.body).append($img);
                    break;
                case "default":
                    break;
            }
        } else if (task.fileType == "audio") {
            item.find("img").remove();
            if (item.$progress) {
                item.$progress.parent().remove();
            }
            var $audio = item.find(".file-audio");
            if ($audio) {
                $audio.show();
            } else {
                $audio = $("<div class=\"file-audio audio-play\"></div>");
                item.append($audio);
            }
            this.loadAudio(task.path, function(data) {
                if (data.success) {
                    $audio.attr("audio_key", data.key);
                }
            });
            $audio.unbind("click").bind("click", function(event) {
                var audioKey = $(this).attr("audio_key");
                if ($.isNotBlank(audioKey)) {
                    var playing = $(this).attr("playing");
                    if (!$.isNotBlank(playing) || playing == "false") {
                        // 暂停其他正在播放的音频
                        $(".file-audio").each(function() {
                            var audioKey = $(this).attr("audio_key");
                            if ($.isNotBlank(audioKey)) {
                                var playing = $(this).attr("playing");
                                if (playing == "true") {
                                    $(this).attr("playing", false);
                                    $(this).removeClass("audio-stop").addClass("audio-play");
                                    $(this).hide().show(0);
                                }
                            }
                        });

                        // 从头播放音频
                        _this.playAudio(audioKey, "play");
                        $(this).attr("playing", true);
                        $(this).removeClass("audio-play").addClass("audio-stop");

                        $(this).hide().show(0);
                    } else if (playing == "true") {
                        // 暂停音频
                        _this.playAudio(audioKey, "pause");
                        $(this).attr("playing", false);
                        $(this).removeClass("audio-stop").addClass("audio-play");

                        $(this).hide().show(0);
                    }
                }
                event.preventDefault();
                event.stopPropagation();
            });

            setTimeout(function() {
                $audio.trigger("click");
            }, 500);
        }

        // 处理回调
        if (task.onComplete && typeof(task.onComplete) == "function") {
            task.onComplete.call(this, task);
        }
    };
    //下载功能end

    // 浏览控制支持，请勿直接调用
    DefaultProxy.prototype.goBackward = function(callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_BACKWARD, {}, callback);
    };

    // 浏览控制支持，请勿直接调用
    DefaultProxy.prototype.showNewWin = function(params, callback) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_NEWWIN, params, callback);
    };

    // 浏览控制支持，请勿直接调用
    DefaultProxy.prototype.cancel = function(params) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_CANCEL, params, null);
    };

    // 浏览控制支持，请勿直接调用
    DefaultProxy.prototype.cancelAll = function(params) {
        this.helper.proxyExecute(this.scheme, this.proxyName, DefaultProxy.METHOD_CANCEL_ALL, params, null);
    };

    return DefaultProxy;
});